import { defineStore } from 'pinia'
import { usePermissionStore, useRouterStore, useUserStore } from '@/store'

export const useAuthStore = defineStore('auth', {
  state: (): { accessToken: string | null; refreshToken: string | null } => ({
    accessToken: null,
    refreshToken: null,
  }),
  actions: {
    setToken({ accessToken, refreshToken }: { accessToken: string; refreshToken: string }) {
      this.accessToken = accessToken
      this.refreshToken = refreshToken
    },
    toLogin() {
      const { router, route } = useRouterStore()
      router
        .replace({
          path: '/login',
          query: route.query,
        })
        .then(() => {})
    },
    resetToken() {
      this.$reset()
    },
    resetLoginState() {
      const { resetUser } = useUserStore()
      const { resetRouter } = useRouterStore()
      const { resetPermission, accessRoutes } = usePermissionStore()

      resetRouter(accessRoutes)

      resetPermission()

      resetUser()

      this.resetToken()
    },
    logout() {
      this.resetLoginState()
      this.toLogin()
    },
  },
  persist: {
    key: 'lingxi',
  },
})
